Javascript의 클래스

✒️ 2025-05-23 17:00 내용 수정

Node.js 교과서 개정 3판 내용 정리 추가


클래스

Javascript에서 객체를 생성하기 위한 탬플릿

class ClassName{
    // constructor
    constructor(key1, key2) {
        this.key1 = key1;
        this.key2 = key2;
    }
    
    // method
    functionName(param) { // function 키워드를 제외하고, 함수 이름과 매개변수만 작성
        console.log(`key1 : ${this.key1} / key2 : ${this.key2} / param : ${param}`)
    }
}

// 객체 생성
let test = new ClassName(key1, key2);

// 객체의 함수 호출
test.functionName(param);
class ClassName{
    constructor(key1, key2) {
        this.key1 = key1; // method 내에서 인스턴스의 속성 정의
        this.key2 = key2;
    }
}

클래스 선언

class ClassName{
    // constructor
    constructor(key1, key2) {
        this.key1 = key1;
        this.key2 = key2;
    }
    
    // method
    functionName(param) { // function 키워드를 제외하고, 함수 이름과 매개변수만 작성
        console.log(`key1 : ${this.key1} / key2 : ${this.key2} / param : ${param}`)
    }
}

클래스 표현식

// 이름이 없는 경우
let test = class {
	constructor(key1, key2) {
		this.key1 = key1;
		this.key2 = key2;
	}
}

console.log(test.name);

// 이름이 있는 경우
let test2 = class  Test{
	constructor(key1, key2) {
		this.key1 = key1;
		this.key2 = key2;
	}
}

생성자

class ClassName{
    // constructor
    constructor(key1, key2) {
        this.key1 = key1;
        this.key2 = key2;
    }
}

정적 메소드

class Test{
    // constructor
    constructor(key1, key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

	// static method
	static info(name) {
		console.log(name);
	}
}

// Test 클래스를 인스턴스화 하지 않고 바로 info()를 호출할 수 있다.
Test.info('hi');
class Test {
	info() {
		return this;
	}
}

let test = new Test();
console.log(test.info()); // Test {}

let info_test = test.info; // test 객체의 메소드를 가져와서 지정
console.log(info_test()); // undefined
class Test {
    static name = 20;
}

let test = new Test();
console.log(test.name); // undefined

test.name = 10;
console.log(test.name); // 10

필드 선언

class ClassName {
	field1 = 0; // 필드 선언
	field2;

	constructor(field1, field2) {
		this.field1 = field1; 
		this.field2 = field2;
	}
}
class ClassName {
	#field1 = 0; // 필드 선언
	#field2;

	constructor(field1, field2) {
		this.#field1 = field1; 
		this.#field2 = field2;
	}
}

클래스 추상화